from django import forms
from django.contrib.auth.models import User


class LoginFrom(forms.Form):
    # 设置样式之前
    # username = forms.CharField(label='用户名', max_length=32)
    # password = forms.CharField(label='密码', min_length=6, widget=forms.PasswordInput())

    # widget = forms.TextInput：设置小部件的类型
    username = forms.CharField(label='用户名', max_length=32, widget=forms.TextInput(attrs={
        'class': 'input', 'placeholder': '用户名/邮箱'
    }))
    password = forms.CharField(label='密码', min_length=6, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '密码'
    }))

    # 验证用户名和密码是否一致
    def clean_password(self):
        # 获取用户名
        username = self.cleaned_data.get('username')
        # 获取密码
        password = self.cleaned_data.get('password')

        if username == password:
            raise forms.ValidationError('用户名与密码不能相同')

        return password


class RegisterForm(forms.ModelForm):
    """注册表单"""
    email = forms.EmailField(label='邮箱', min_length=3, widget=forms.EmailInput(attrs={
       'class': 'input', 'placeholder': '用户名/邮箱'
    }))
    # 避免密码明文显示
    password = forms.CharField(label='密码', min_length=6, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '密码'
    }))
    password1 = forms.CharField(label='再次输入密码', min_length=6, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '再次输入密码'
    }))

    class Meta:
        model = User
        fields = ('email', 'password')

    # 对新注册的用进行邮箱验证，主要是验证新注册的用户邮箱是否存在，使用邮箱进行注册，就不需要使用username，需要使用email
    def clean_email(self):
        # 获取用户名
        email = self.cleaned_data.get('email')
        # 判断新增的用户名是否已经在数据库中存在了
        exists = User.objects.filter(email=email).exists()

        if exists:
            raise forms.ValidationError('用户名已经存在！')

        return email

    # 验证两次输入的密码是否一致
    def clean_password1(self):

        if self.cleaned_data['password'] != self.cleaned_data['password1']:
            raise forms.ValidationError('两次输入的密码不一致！')

        return self.cleaned_data['password1']


class ForgetPwdForm(forms.Form):
    """找回密码时，填写邮箱地址的表单"""
    email = forms.EmailField(label='请输入注册邮箱地址', min_length=4, widget=forms.EmailInput(attrs={
        'class': 'input', 'placeholder': '用户名/邮箱'
    }))


# 这个表单使用时，需要在views.py中引入
class ModifyPwdForm(forms.Form):
    """找回密码时，重新设置密码的表单"""
    # 避免密码明文显示
    password = forms.CharField(label='输入新密码', min_length=6, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '输入密码'
    }))
    password1 = forms.CharField(label='确认输入密码', min_length=6, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '输入密码'
    }))

    # 验证两次输入的密码是否一致
    def clean_password1(self):
        if self.cleaned_data['password'] != self.cleaned_data['password1']:
            raise forms.ValidationError('两次输入的密码不一致！')

        return self.cleaned_data['password1']
